"ui";
importClass(android.graphics.BitmapFactory);
importClass(android.graphics.Paint);

// 显示主页面
showMainPage();

//创建选项菜单(右上角)
ui.emitter.on("create_options_menu", menu => {
  menu.add("新增");
  menu.add("删除");
});
//监听选项菜单点击
ui.emitter.on("options_item_selected", (e, item) => {
  const title = item.getTitle();
  if (title === '新增') {
    showAddPage();
  } else if (title === '删除') {
    deletePage();
  }
  e.consumed = true;
});

// 主页面方法
function showMainPage() {
  ui.layout(
    <drawer id="drawer">
      <vertical>
        <appbar>
          <toolbar id="toolbar" title="" />
          <tabs id="tabs" />
        </appbar>
        <viewpager id="viewpager">
          <frame>
            <horizontal>
              <list id="mobileList" w="*">
                <card w="*" h="250" margin="10 5" cardCornerRadius="2dp">
                  <vertical>
                    <img id="logo" src="{{filePath}}" w="200" h="200" gravity="center"></img>
                    <text id="title1" text="{{userName}}" textColor="#222222" textSize="16sp" maxLines="1" textStyle="bold" gravity="center" />
                  </vertical>
                </card>
              </list>
            </horizontal>
          </frame>
          <frame>
            <list id="wechatList" w="*">
              <card w="*" h="250" margin="10 5" cardCornerRadius="2dp">
                <vertical>
                  <img id="logo" src="{{filePath}}" w="200" h="200" gravity="center"></img>
                  <text id="title1" text="{{userName}}" textColor="#222222" textSize="16sp" maxLines="1" textStyle="bold" gravity="center" />
                </vertical>
              </card>
            </list>
          </frame>
        </viewpager>
      </vertical>
    </drawer>
  );
  //设置滑动页面的标题
  ui.viewpager.setTitles(["😡电话", "🍏微信"]);
  //让滑动页面和标签栏联动
  ui.tabs.setupWithViewPager(ui.viewpager);
  // 设置标题
  activity.setSupportActionBar(ui.toolbar);
  const storage = storages.create("autowechat");
  const mobileData = JSON.parse(storage.get("mobile") || '[]');
  const wechatData = JSON.parse(storage.get("wechat") || '[]');
  ui.mobileList.setDataSource(mobileData);
  ui.wechatList.setDataSource(wechatData);

  // 打电话
  ui.mobileList.on("item_click", function (item, i, itemView, listView) {
    const mobile = mobileData[i];
    shell('am start -a android.intent.action.CALL -d tel:' + mobile.userMobile, true);
  });

  // 打微信
  ui.wechatList.on("item_click", function (item, i, itemView, listView) {
    const wechat = wechatData[i];
    wechatVideo(wechat.userName);
  });
}

// 新增方法
function showAddPage() {
  let filePath = '';
  ui.layout(
    <ScrollView>
      <vertical>
        <text textSize="18sp" textColor="#000000" margin="20" textStyle="bold">
          添加信息
        </text>

        <text textSize="16sp" margin="8">请选择添加电话/微信</text>
        <horizontal>
          <checkbox id="mobile" text="电话" marginLeft="16" checked="true" />
          <checkbox id="wechat" text="微信" marginLeft="16" checked="true" />
        </horizontal>

        <text textSize="16sp" margin="8">请输入联系人姓名(与微信名称必须一致)</text>
        <input id="userName" text="" inputType="text" margin="0 16" />

        <text textSize="16sp" margin="8">请输入联系人电话(选择电话时必填)</text>
        <input id="userMobile" text="" inputType="number" margin="0 16" />

        <text textSize="16sp" margin="8">请选择联系人的头像</text>
        <horizontal id="parentView" w="150" h="150"></horizontal>
        <button margin="16" id="chooseImage">选择头像</button>

        <linear gravity="center">
          <button margin="16" id="save" style="Widget.AppCompat.Button.Colored">保存</button>
          <button margin="16" id="cancel">取消</button>
        </linear>
      </vertical>
    </ScrollView>
  );
  //   选择照片
  ui.chooseImage.click(function () {
    let fileType = "image/*";
    let requestCode = 1;
    var intent = new Intent();
    intent.setType(fileType);
    intent.setAction(Intent.ACTION_GET_CONTENT);
    activity.startActivityForResult(intent, requestCode);
    activity.getEventEmitter().on("activity_result", (requestCode, resultCode, data) => {
      if (resultCode != -1) {
        toastLog("没有选择文件!");
        return false;
      } else {
        var uri = data.getData();
        log("uri: %s", uri.toString());
        filePath = URIUtils_uriToFile(uri);
        log(filePath);
        var cr = context.getContentResolver();
        var bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
        log("bitmap: %s", bitmap);
        ui.parentView.removeAllViews();
        var childView = ui.inflate(<img w="*" gravity="center"></img>, ui.parentView);
        ui.parentView.addView(childView);
        childView.setImageBitmap(bitmap);
      }
    });
  });
  ui.save.click(function () {
    const mobileFlag = ui.mobile.isChecked();
    const wechatFlag = ui.wechat.isChecked();
    const userName = ui.userName.text();
    const userMobile = ui.userMobile.text();
    if (!mobileFlag && !wechatFlag) {
      alert('请至少勾选电话、微信中的一项');
      return false;
    }

    if (!userName) {
      alert('请输入联系人姓名');
      return false;
    }

    if (mobileFlag && !userMobile) {
      alert('请输入联系人电话');
      return false;
    }

    if (!filePath) {
      alert('请选择联系人头像');
      return false;
    }

    var storage = storages.create("autowechat");
    let mobiles = JSON.parse(storage.get("mobile") || '[]');
    let wechats = JSON.parse(storage.get('wechat') || '[]');

    if (mobileFlag) {
      mobiles.push({
        id: Math.floor(Math.random() * 100000),
        userName: userName,
        userMobile: userMobile,
        filePath: 'file://' + filePath
      });
    }

    if (wechatFlag) {
      wechats.push({
        id: Math.floor(Math.random() * 100000),
        userName: userName,
        userMobile: userMobile,
        filePath: 'file://' + filePath
      });
    }

    storage.put('mobile', JSON.stringify(mobiles));
    storage.put('wechat', JSON.stringify(wechats));

    toastLog('保存成功');

    setTimeout(() => cancel(), 500);
  });
  ui.cancel.click(function () {
    cancel();
  });
}

// 删除方法
function deletePage() {
  ui.layout(
    <ScrollView>
      <vertical>
        <text textSize="16sp" margin="8">请选择删除的人</text>
        <list id="deleteList">
          <checkbox id="{{id}}" text="{{userName}}" marginLeft="16" checked="false" />
        </list>
        <linear gravity="center">
          <button margin="16" id="delete" style="Widget.AppCompat.Button.Colored">删除</button>
          <button margin="16" id="cancel">取消</button>
        </linear>
      </vertical>
    </ScrollView>
  );
  // 收集名称
  var storage = storages.create("autowechat");
  let mobiles = JSON.parse(storage.get("mobile") || '[]');
  let wechats = JSON.parse(storage.get('wechat') || '[]');
  const deleteIds = new Set();

  // 修改显示的名字
  mobiles.forEach(mobile => {
    mobile.userName = '电话：' + mobile.userName;
  });
  wechats.forEach(wechat => {
    wechat.userName = '微信：' + wechat.userName;
  });
  let userInfos = mobiles.concat(wechats);
  ui.deleteList.setDataSource(userInfos);
  // 监听勾选情况
  ui.deleteList.on("item_click", function (item, i, itemView, listView) {
    if (deleteIds.has(item.id)) {
      deleteIds.delete(item.id);
    } else {
      deleteIds.add(item.id);
    }
  });
  // 点击删除按钮
  ui.delete.click(function () {
    for (let i = mobiles.length - 1; i >= 0; i--) {
      let mobile = mobiles[i];
      mobiles[i].userName = mobiles[i].userName.replace('电话：', '');
      if (deleteIds.has(mobile.id)) {
        mobiles.splice(i, 1);
      }
    }

    for (let i = wechats.length - 1; i >= 0; i--) {
      let wechat = wechats[i];
      wechats[i].userName = wechats[i].userName.replace('微信：', '');
      if (deleteIds.has(wechat.id)) {
        wechats.splice(i, 1);
      }
    }
    // 存储
    storage.put('mobile', JSON.stringify(mobiles));
    storage.put('wechat', JSON.stringify(wechats));
    toastLog('保存成功');

    // 回到首页
    showMainPage();
  });
  // 取消
  ui.cancel.click(function () {
    showMainPage();
  });
}

function deleteUser() {

}

function cancel() {
  ui.userName.setText('');
  ui.userMobile.setText('');
  ui.parentView.removeAllViews();
  showMainPage();
}

function URIUtils_uriToFile(uri) {
  var r = null,
    cursor,
    column_index,
    selection = null,
    selectionArgs = null,
    isKitKat = android.os.Build.VERSION.SDK_INT >= 19,
    docs;
  if (uri.getScheme().equalsIgnoreCase("content")) {
    if (isKitKat && android.provider.DocumentsContract.isDocumentUri(activity, uri)) {
      if (String(uri.getAuthority()) == "com.android.externalstorage.documents") {
        docs = String(android.provider.DocumentsContract.getDocumentId(uri)).split(":");
        if (docs[0] == "primary") {
          return android.os.Environment.getExternalStorageDirectory() + "/" + docs[1];
        }
      } else if (String(uri.getAuthority()) == "com.android.providers.downloads.documents") {
        uri = android.content.ContentUris.withAppendedId(
          android.net.Uri.parse("content://downloads/public_downloads"),
          parseInt(android.provider.DocumentsContract.getDocumentId(uri))
        );
      } else if (String(uri.getAuthority()) == "com.android.providers.media.documents") {
        docs = String(android.provider.DocumentsContract.getDocumentId(uri)).split(":");
        if (docs[0] == "image") {
          uri = android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        } else if (docs[0] == "video") {
          uri = android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
        } else if (docs[0] == "audio") {
          uri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        }
        selection = "_id=?";
        selectionArgs = [docs[1]];
      }
    }
    try {
      cursor = activity.getContentResolver().query(uri, ["_data"], selection, selectionArgs, null);
      if (cursor && cursor.moveToFirst()) {
        r = String(cursor.getString(cursor.getColumnIndexOrThrow("_data")));
      }
    } catch (e) {
      log(e);
    }
    if (cursor) cursor.close();
    return r;
  } else if (uri.getScheme().equalsIgnoreCase("file")) {
    return String(uri.getPath());
  }
  return null;
}

// 打开微信视频聊天
function wechatVideo(userName) {
  threads.start(function wx() {
    // 设置分辨率
    setScreenMetrics(1080, 2340);
    sleep(200);
    // 杀掉微信
    shell('am force-stop com.tencent.mm', true);
    sleep(200);
    console.log('杀掉微信进程');
    // 获取无障碍权限
    shell(
      'settings put secure enabled_accessibility_services com.blink.autowechat/com.stardust.autojs.core.accessibility.AccessibilityService',
      true
    );
    sleep(500);
    home();
    sleep(500);
    // 启动微信
    app.launchPackage('com.tencent.mm');

    sleep(8000);
    // 点击搜索
    click(890, 150);
    sleep(5000);
    // 输入搜索文本
    setText(userName);
    // input(userName);
    sleep(2500);
    // 选择第一个
    click(680, 340);
    sleep(1500);
    // 点击输入框
    click(540, 2130);
    sleep(1000);
    // 点击加号
    click(1017, 1300);
    sleep(1500);
    // 点击视频
    click(635, 1580);
    // 点击视频通话
    sleep(1500);
    click(538, 1800);
  });

}
